package api.Order;

import DAO.Cuisine;
import DAO.Order;
import club.kingon.sql.builder.SqlBuilder;
import club.kingon.sql.builder.enums.Operator;
import com.alibaba.fastjson2.JSON;
import util.DBConnector;
import util.StanderRES;

import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

public class ImplUseOrder implements UseOrder{
    @Override
    public String addOrder(String order) {
        Order the_order = JSON.parseObject(order, Order.class);
        List<Cuisine> cuisines = JSON.parseArray(String.valueOf(the_order.getCuisines()), Cuisine.class);
        AtomicReference<Float> sump = new AtomicReference<>(0F);
        cuisines.forEach(the_cuisine -> sump.updateAndGet(v -> v + the_cuisine.getCuisinePrise()));

        Integer result = DBConnector.result(

                C -> C.createQuery(SqlBuilder.insertInto("Orders","userId","cuisines","totalPrise").values().addValue(the_order.getUserId(),the_order.getCuisines(),sump).build()).executeUpdate().getResult()
        );
//        System.out.println(o);
        return StanderRES.RES(StanderRES.Status.OK, result);
    }

    @Override
    public String getOrderById(Integer id) {
        Order result = DBConnector.result(C -> C.createQuery(SqlBuilder.selectAll().from(Order.class).where(Order::getId, Operator.EQ, id).build()).executeAndFetch(Order.class).get(0));

        return StanderRES.RES(StanderRES.Status.OK, result);
    }

    @Override
    public String getUserOrderById(String id) {
        Order result = DBConnector.result(C -> C.createQuery(SqlBuilder.selectAll().from(Order.class).where(Order::getUserId, Operator.EQ, id).build()).executeAndFetch(Order.class).get(0));
        return StanderRES.RES(StanderRES.Status.OK, result);
    }
}
